package com.hdu;


import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;


@Slf4j
@Getter
public class EatFishGame {


    public static void main(String[] args) throws InterruptedException {
        EatFishGame eatFishGame = new EatFishGame();
        eatFishGame.init(10000000, 9);
        eatFishGame.start();
        Thread.sleep(1000);
        log.info("一共吃了 : {} 条鱼", eatFishGame.getEatFishCount().get());
    }

    private AtomicInteger fishCount;
    private AtomicInteger eatFishCount;
    private int catCount;


    public void init(int fishCount, int catCount) {
        this.eatFishCount = new AtomicInteger(0);
        this.fishCount = new AtomicInteger(fishCount);
        this.catCount = catCount;
    }

    public void start() {
        for (int i = 0; i < catCount; i++) {
            new Cat().start();
        }
    }

    class Cat extends Thread {

        @Override
        public void run() {
            eat();
        }


        void eat() {
            while (fishCount.get() > 0) {
                // 当前鱼的数量
                int curFishCount = fishCount.get();
                // 鱼的数量的一半
                int halfFishCount = curFishCount == 1 ? 1 : curFishCount / 2;
                // 剩下鱼的数量
                int leftFishCount = curFishCount - halfFishCount;
                if (fishCount.compareAndSet(curFishCount, leftFishCount)) {
                    log.info("吃了 {} 条鱼", halfFishCount);
                    eatFishCount.addAndGet(halfFishCount);
                }
            }
        }
    }

}




